package com.first.xiinn.filter;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.apache.struts2.StrutsStatics;

import com.first.core.web.Constants;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

public class LoginInterceptor extends AbstractInterceptor {
	
	Logger log = Logger.getLogger(LoginInterceptor.class.getName());

	//需要登陆验证的页面
	List<String> includePages;

	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		
		ActionContext actionContext = invocation.getInvocationContext();
		HttpServletRequest request= (HttpServletRequest) actionContext.get(StrutsStatics.HTTP_REQUEST);
		Map session = actionContext.getSession();
		
		String currentUrl = request.getRequestURI();//获取当前访问的url
		//只过滤jsp或action请求
		if(currentUrl.indexOf(".vm") > -1 || currentUrl.indexOf(".jsp") > -1 || currentUrl.indexOf(".do") > -1){
			boolean isInclude = false;
			for (Iterator iterator = includePages.iterator(); iterator.hasNext();) {
				String pageOrURL = (String) iterator.next();
				if(currentUrl.indexOf(pageOrURL) > -1 ){
					isInclude = true;
					break;
				}
			}
			
			if(isInclude){
				log.debug("对访问的指定url进行权限验证。" + "请求的URL：" + currentUrl);
				
				if(session == null || session.get(Constants.USER_SESSION_KEY) == null){
					return "login";
				}
			}
		}
		
		return invocation.invoke();
	}

	@Override
	public void init() {
		FileInputStream input;  
        byte buff[]=null;  
        try {  
            input = new FileInputStream(Constants.AUTH_FILEPATH);  
            buff=new byte[input.available()];             
            input.read(buff);  
            input.close();  
              
        } catch (FileNotFoundException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        } catch (IOException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        }         
        /** 
         * 通过开源XStream来解析XML，并转化成Java对象 
         */  
        XStream xstream = new XStream(new DomDriver());   
        xstream.alias("PageList", ArrayList.class);    
        xstream.alias("includePage", String.class);    
        includePages = (List)xstream.fromXML(new String(buff));
		log.debug("初始化权限过滤器。");
		super.init();
	}
	
}